<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"
    />
    <title>view</title>
    <link rel="stylesheet" href="index.css" />
    <link rel="stylesheet" href="/formMarking/formMakingV3/dist/index.css" />

    <script src="vue.global.js"></script>
    <script src="axios.min.js"></script>
    <!-- 微信JS-SDK 兼容微信小程序 引入此文件 -->
    <script src="jweixin-1.4.0.js"></script>
    <!-- uni-app SDK -->
    <script src="uni.webview.1.5.2.js"></script>
    <script src="index.full.js"></script>
    <script src="/formMarking/formMakingV3/dist/form-making-v3.umd.js"></script>

    <script src="request.js"></script>
    <script src="tools.js"></script>
  </head>

  <body>
    <div id="app">
      <div style="padding: 10px">
        <fm-generate-form
          :data="jsonForm"
          :edit="isEdit"
          ref="generateForm"
        ></fm-generate-form>
        <!--
        <div>AppID:{{appID}}</div>
        <div>tableName:{{tableName}}</div>
        <div>rsID:{{rsID}}</div>
        <div>modeID:{{modeID}}</div>-->
        <!--功能区-->
        <div style="padding: 10px">
          <el-button
            type="primary"
            style="width: 30%"
            @click="saveItem"
            v-if="contrlBar.isSave"
            >保存</el-button
          >
          <el-button
            type="primary"
            style="width: 30%"
            @click="delItem"
            v-if="contrlBar.isDel"
            >删除</el-button
          >
          <el-button
            type="success"
            @click="butclick(item)"
            style="width: 100%"
            v-for="(item,key) in dataMeun"
            >{{item.funName}}</el-button
          >
        </div>

        <!--弹出对话框-->
        <el-drawer
          v-model="dialogVisible"
          direction="btt"
          :title="dTitle"
          style="font-size: 14px; padding: 0px"
        >
          <template #default>
            <el-radio-group v-model="radioModel" class="ml-4" v-if="isRadio">
              <el-radio
                :label="item"
                size="large"
                v-for="(item, index) in arrItem"
                >{{item}}</el-radio
              >
            </el-radio-group>

            <el-checkbox-group v-model="radioModel" v-if="!isRadio">
              <el-checkbox :label="item" v-for="(item, index) in arrItem" />
            </el-checkbox-group>
          </template>
          <template #footer>
            <div style="flex: auto">
              <el-button @click="cancelClick" style="width: 100%"
                >取消</el-button
              >
              <el-button
                type="primary"
                @click="confirmClick"
                style="width: 100%"
                >确定</el-button
              >
            </div>
          </template>
        </el-drawer>

        <!--输入弹出框-->
        <el-drawer
          v-model="inputShow"
          direction="btt"
          :title="dTitle"
          style="font-size: 14px; padding: 0px"
        >
          <template #default>
            <el-input v-model="currText" placeholder="请输入内容" />
          </template>
          <template #footer>
            <div style="flex: auto">
              <el-button @click="canleInput" style="width: 100%"
                >取消</el-button
              >
              <el-button
                type="primary"
                @click="confirmInput"
                style="width: 100%"
                >确定</el-button
              >
            </div>
          </template>
        </el-drawer>
      </div>
    </div>
  </body>
  <script>
    const { createApp, ref, nextTick, onMounted, reactive } = Vue;

    const App = {
      setup() {
        const url = ref("https://cjpc.scmvc.cn/api");
        const generateForm = ref();
        const jsonForm = ref();
        const jsonData = ref();
        const appID = ref();
        const tableName = ref();
        const rsID = ref(0);
        const modeID = ref(0);
        const token = ref();
        const dataMeun = ref([]); //底部菜单
        const contrlBar = reactive({ isSave: false, isDel: false });
        const isEdit = ref(true);
        const dialogVisible = ref(false); //对话框控制
        const dTitle = ref("操作面板");
        const arrItem = ref([]);
        const isRadio = ref(true);
        const funID = ref();
        const radioModel = ref();
        const currText = ref();
        const inputShow = ref(false);
        const stateCode = ref(0);
        const unUser = ref([]);
        // const uploadField = ref([]);

        // 在引用依赖的文件后，需要在 HTML 中监听 UniAppJSBridgeReady 事件触发后，才能安全调用 uni 的 API。
        document.addEventListener("UniAppJSBridgeReady", function () {
          uni.getEnv(function (res) {
            //console.log("获取当前环境：" + JSON.stringify(res));
          });
        });

        onMounted(() => {
          var myPar = getURLParameter();
          appID.value = myPar.appID;
          tableName.value = myPar.tableName;
          rsID.value = myPar.rsID;
          modeID.value = myPar.modeID;
          token.value = myPar.token;
          document.title = myPar.title;
          if (myPar.miao) {
            let one = [];
            one = myPar.miao.split(":");
            const newItem = {
              key: one[0], // 这里可以是动态生成的，比如通过prompt或其他方式获取
              value: one[1] // 同样可以是动态生成的
            };
            unUser.value.push(newItem);
            if (myPar.gulu) {
              let one = [];
              one = myPar.gulu.split(":");
              const newItem = {
                key: one[0], // 这里可以是动态生成的，比如通过prompt或其他方式获取
                value: one[1] // 同样可以是动态生成的
              };
              unUser.value.push(newItem);
            }
          }
          axios({
            url: url.value + "/Analysis/getStructAndData",
            method: "post",
            data: {
              appID: appID.value,
              rsID: rsID.value,
              modeID: modeID.value
            },
            headers: {
              "Content-Type": "application/json",
              Authorization: "Bearer " + token.value
            }
          })
            .then(res => {
              jsonForm.value = JSON.parse(res.data.dataList.formStruct);
              jsonData.value = JSON.parse(res.data.dataList.formData);
              var postDatas = {
                message: "初始化时传给终端数据",
                formStruct: jsonForm.value,
                formData: jsonData.value
              };
              parent.postMessage(JSON.stringify(postDatas), "*");

              nextTick(() => {
                generateForm.value.refresh();
                if (res.data.dataList.hideFields != null) {
                  generateForm.value.hide(res.data.dataList.hideFields);
                }
                if (res.data.dataList.enabledFields != null) {
                  generateForm.value.disabled(
                    res.data.dataList.enabledFields,
                    true
                  );
                }
                // 当下次执行
                jsonForm.value.list.forEach(item => {
                  if (item.type === "imgupload" || item.type === "fileupload") {
                    console.log("find imgupload component, name=" + item.name);
                    generateForm.value.setOptions(item.name, {
                      headers: [
                        {
                          key: "Authorization",
                          value: "Bearer " + token.value
                        }
                      ]
                    });
                  }

                  if (item.columns != null && item.columns.length > 0) {
                    item.columns.forEach(column => {
                      if (column.list.length > 0) {
                        column.list.forEach(columnItem => {
                          if (
                            columnItem.type === "imgupload" ||
                            columnItem.type === "fileupload"
                          ) {
                            console.log(
                              "find imgupload in column item, name=" +
                                columnItem.name +
                                ", token=" +
                                token.value
                            );
                            generateForm.value.setOptions([columnItem.name], {
                              headers: [
                                {
                                  key: "Authorization",
                                  value: "Bearer " + token.value
                                }
                              ]
                            });
                          }
                        });
                      }
                    });
                  }
                });
              });

              if (jsonData.value != null && jsonData.value != "") {
                //表单赋值,因后台传过来的是一个数组，所以这里要添加0
                //jsonData.value[0] = jsonData.value[0].replace('http://192.168.18.32:8185', 'https://paxy.scmvc.cn');
                generateForm.value.setData(jsonData.value[0]);

                stateCode.value = jsonData.value[0].stateCode;
              }
              //开始解析功能列表

              dataMeun.value.length = 0;

              if (
                (res.data.result.isUpdate || rsID.value == 0) &&
                stateCode.value < 100
              ) {
                contrlBar.isSave = true;
              } else {
                isEdit.value = false;
              }

              if (
                res.data.result.isDel &&
                rsID.value != 0 &&
                stateCode.value < 100
              ) {
                contrlBar.isDel = true;
              }

              res.data.result.appFunctions.forEach(e => {
                if (e.showType == 1 && e.disPhone != 1) {
                  dataMeun.value.push({
                    funIcon: e.funIcon,
                    funName: e.funName,
                    id: e.id,
                    contrlFalg: e.contrlFalg,
                    contrlTable: e.contrlTable
                  });
                }
                //buttSize.value++;
              });
            })
            .catch(err => {
              console.log(err, "err");
            });
        });

        //保存功能
        const saveItem = () => {
          generateForm.value.getData().then(data => {
            if (unUser.value.length != 0) {
              for (let index = 0; index < unUser.value.length; index++) {
                const element = unUser.value[index];
                const need = element.key;
                data[need] = element.value;
                //parent.postMessage(JSON.stringify(data), "*");
              }
            }
            axios({
              url: url.value + "/Analysis/saveFormData",
              method: "post",
              data: {
                rsID: rsID.value,
                jsonStr: JSON.stringify(data),
                tableName: tableName.value,
                isSheng: false,
                editCode: 0
              },
              headers: {
                "Content-Type": "application/json",
                Authorization: "Bearer " + token.value
              }
            })
              .then(res => {
                if (res.data.isSuccess) {
                  uni.webView.postMessage({
                    data: { type: 1, msg: "保存成功" }
                  });

                  // if window is in iframe, postMessage
                  if (window.top != window.self) {
                    // var postData = {
                    //   message: "saveIframe",
                    //   formStruct: jsonForm.value,
                    //   formData: jsonData.value
                    // };
                    // console.log("postData = " + postData);
                    // 当前页面在iframe才postMessage
                    parent.postMessage("saveIframe", "*");
                  } else {
                    uni.navigateBack();
                  }
                } else {
                  alert(res.data.msg);
                }
              })
              .catch(err => {
                console.log("error", err);
              });
          });
        };
        //删除功能
        const delItem = () => {
          axios({
            url: url.value + "/Analysis/delFormData",
            method: "post",
            params: { ids: rsID.value, tableName: tableName.value },
            headers: {
              "Content-Type": "application/json",
              Authorization: "Bearer " + token.value
            }
          })
            .then(res => {
              if (res.data.isSuccess) {
                uni.webView.postMessage({
                  data: { type: 1, msg: "删除成功！" }
                });

                // if window is in iframe, postMessage
                if (window.top != window.self) {
                  // 当前页面在iframe才postMessage
                  parent.postMessage("deleteIframe", "*");
                } else {
                  uni.navigateBack();
                }
                // uni.navigateBack();
              } else {
                alert(res.data.msg);
                console.error("error", res.data.msg);
              }
            })
            .catch(err => {
              console.error("error", err);
            });
        };
        //通用功能执行
        const butclick = item => {
          if (item.contrlFalg == 1) {
            axios({
              url: url.value + "/Analysis/exeFormFunction",
              method: "post",
              data: {
                funID: item.id,
                tableName: item.funName,
                ids: rsID.value,
                currText: ""
              },
              headers: {
                "Content-Type": "application/json",
                Authorization: "Bearer " + token.value
              }
            })
              .then(res => {
                if (res.data.isSuccess) {
                  uni.webView.postMessage({
                    data: { type: 1, msg: res.data.msg }
                  });

                  uni.navigateBack();
                } else {
                  alert(res.data.msg);
                }
              })
              .catch(err => {
                console.error("err", err);
              });
          } else if (item.contrlFalg == 2) {
            //表示用户输入的情况
            inputShow.value = true;
            funID.value = item.id;
          } else if (item.contrlFalg == 3) {
            if (item.contrlTable.indexOf("$") !== -1) {
              arrItem.value = item.contrlTable.split("$");
              isRadio.value = true;
            } else {
              arrItem.value = item.contrlTable.split("#");
              isRadio.value = false;
            }
            funID.value = item.id;
            dialogVisible.value = true;
          } else {
            console.error("error", item);
          }
        };

        //提交对话框数据
        const confirmClick = () => {
          currText.value = "";
          if (!isRadio.value) {
            radioModel.value.forEach(el => {
              currText.value += el + ",";
            });
            currText.value = currText.value.substring(
              0,
              currText.value.length - 1
            );
          } else {
            currText.value = radioModel.value;
          }

          axios({
            url: url.value + "/Analysis/exeFormFunction",
            method: "post",
            data: {
              funID: funID.value,
              tableName: "",
              ids: rsID.value,
              currText: currText.value
            },
            headers: {
              "Content-Type": "application/json",
              Authorization: "Bearer " + token.value
            }
          })
            .then(res => {
              if (res.data.isSuccess) {
                dialogVisible.value = false;
                uni.webView.postMessage({
                  data: { type: 1, msg: res.data.msg }
                });

                uni.navigateBack();
              } else {
                alert(res.data.msg);
              }
            })
            .catch(err => {
              alert(err);
              console.error(err);
            });
        };

        const cancelClick = () => {
          dialogVisible.value = false;
        };

        //关闭输入框
        const canleInput = () => {
          inputShow.value = false;
        };

        //提交数据
        const confirmInput = () => {
          axios({
            url: url.value + "/Analysis/exeFormFunction",
            method: "post",
            data: {
              funID: funID.value,
              tableName: "",
              ids: rsID.value,
              currText: currText.value
            },
            headers: {
              "Content-Type": "application/json",
              Authorization: "Bearer " + token.value
            }
          })
            .then(res => {
              if (res.data.isSuccess) {
                inputShow.value = false;
                uni.webView.postMessage({
                  data: { type: 1, msg: res.data.msg }
                });

                uni.navigateBack();
              } else {
                alert(res.data.msg);
              }
            })
            .catch(err => {
              alert(err);
            });
        };
        //导出所有响应式变量
        return {
          appID,
          rsID,
          tableName,
          modeID,
          generateForm,
          jsonForm,
          contrlBar,
          dataMeun,
          saveItem,
          delItem,
          butclick,
          isEdit,
          dialogVisible,
          dTitle,
          isRadio,
          arrItem,
          radioModel,
          confirmClick,
          cancelClick,
          inputShow,
          canleInput,
          confirmInput,
          currText
        };
      }
    };

    const app = createApp(App).use(ElementPlus).use(FormMakingV3).mount("#app");
  </script>
</html>
